<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Главная </title>
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/>
<link rel="stylesheet" type="text/css" href="/css/template.css"/>
<link rel="stylesheet" type="text/css" href="/css/gallery.css"/>
<link rel="stylesheet" type="text/css" href="/css/dark.css"/>
<link rel="stylesheet" type="text/css" href="/css/buttons.css"/>
<link href='http://fonts.googleapis.com/css?family=Lobster&subset=latin,cyrillic' rel='stylesheet' type='text/css'>

<script type="text/javascript" src="/js/jquery-1.8.2.js"></script>
<script type="text/javascript" src="/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="/js/jquery.easing.compatibility.js"></script>
<script type="text/javascript" src="/js/jquery.lavalamp.min.js"></script>

<script type="text/javascript" src="/js/myriad.js"></script>
<script type="text/javascript" src="/js/menu.js"></script>
<script type="text/javascript" src="/js/validation.js"></script>

<script type="text/javascript">


var Order = {
    order:null
}

Order.order = {
    price:null ,
    id:null,
    amount:null
}
var myOrders = [];
var orderList;
var totalSum = 0;
var container;
var order_container;

function init() {
    orderList = $("#list");
    container = $('.credential_container');
    order_container = $('.result_order_container');

    $('#close').bind('click', function() {
        order_container.animate({
            marginTop:"-400"
        }, 1000, function() {
            $('.open').fadeIn(1000);
        });
    });

    $('.open').bind('click', function() {
        $('.open').fadeOut(1000, function() {
            order_container.animate({
                marginTop:"0"
            });
        })
    });
}
if ($.browser.opera) {
    window.onload = function() {
        init();
    }
} else {
    $("document").ready(function() {
        init();
    });
}

Order.add = function(order) {
    myOrders.push(order);
}

Order.updateOrder = function(id, amount, price) {
    if ($(amount).val() != 0) {
        if ($("#absolute_container").css("display") == "none") {
            $("#absolute_container").css("display", "block");
            $("#absolute_container").animate({
                marginTop:"0"
            }, 1500);
        }
        var isAdded = false;
        for (var i = 0; i < myOrders.length; i++) {

            var tempOrder = myOrders[i];
            if (tempOrder != null) {
                if (tempOrder.id == id) {
                    myOrders[i].amount = $(amount).val();
                    $('#order_list_item_' + tempOrder.id).remove();
                    tempOrder = null;
                    isAdded = true;

                    break;
                }
            }
        }
        var order = {
            id : id,
            amount : $(amount).val(),
            price : price
        }
        if (!isAdded) {
            Order.add(order);
            isAdded = false;
        }
        Order.getLanternTitle(order);
        Order.calculateSum(myOrders);
    }
}

Order.getLanternTitle = function(order) {
    $.ajax({
        type:"GET",
        url:"/lantern/get_lantern_by_id.html",
        data:{id:order.id},
        success:function(data) {
            orderList = $("#list");
            //  console.log(data);
            try {
                var row = $("<li id='order_list_item_" + order.id + "'></li>").html(data + "&nbsp;&nbsp;&nbsp;" + order.amount +
                        "&nbsp;*&nbsp;" + order.price + "&nbsp;&nbsp;<img src='/img/icons/minus.png' style='cursor:pointer;'onclick='Order.deleteOrder(" + order.id + ");' width='12px'/>");
                row.appendTo(orderList);
            } catch(e) {
                //   console.log(e);
            }
            //TODO: get lantern name and set it into order lantern_title container
        },error:function() {

        }
    })
}

Order.deleteOrder = function(id) {
    for (var i in myOrders) {
        if (myOrders[i] != null) {
            if (myOrders[i].id == id) {
                myOrders[i] = null;
                $('#order_list_item_' + id).remove();
                Order.calculateSum(myOrders);
            }
        }
    }
}

Order.calculateSum = function(orders) {
    totalSum = 0;
    for (var i in orders) {
        var order = orders[i];
        if (order != null)
            totalSum += parseInt(order.amount) * parseInt(order.price);
    }
    $('.total_sum').html("Итого:&nbsp" + totalSum);
}

Order.showCred = function() {

    order_container.animate({
        marginTop:-order_container.height()
    }, 1000);
    container.animate({
        marginTop:"0"
    }, 1500);
}

Order.sendOrder = function(orders) {
    if (orders.length != 0) {

        var jsonStart = "{\"orders\":[";
        var jsonEnd = "]}";
        var jsonBody = "";
        for (i in orders) {
            var order = orders[i];
            if (order != null) {
                jsonBody += "{\"lantern\":{\"idLantern\":" + order.id + "},\"amount\":" + order.amount + "}"
                if (i != orders.length - 1) {
                    jsonBody += ",";
                }
            }
        }
        var resultJson = jsonStart + jsonBody + jsonEnd;
        // console.log(resultJson);
        var email = $('#cred_email').val();
        var phone = $('#cred_phone').val();
    <sec:authorize ifAnyGranted="ROLE_ANONYMOUS">
        if (email == "" || !isValidEmailAddress(email)) {
            alert("Введите корректный Email адрес!");
            return;
        }

        if (phone == "" || !isValidPhone(phone)) {
            alert("Введите корректный номер телефона!");
            return;

        }
    </sec:authorize>
        $.ajax({
            url:"/order/make_order.html",
            type:"POST",
            <sec:authorize ifAnyGranted="ROLE_ANONYMOUS">
            data:{orders:resultJson, phone:phone, email:email},
            </sec:authorize>
            <sec:authorize ifNotGranted="ROLE_ANONYMOUS">
            data:{orders:resultJson, phone:"${user.phone}", email:"${user.email}"},
            </sec:authorize>
            success:function(json) {
                //  console.log(json);
                if (json.errorCode == 0) {
                <sec:authorize ifAnyGranted="ROLE_ANONYMOUS">
                    var container = $('.credential_container');
                    container.animate({
                        marginTop:"-400"
                    }, 1000, function() {
                        container.css("display", "none");
                    });
                </sec:authorize>
                <sec:authorize ifNotGranted="ROLE_ANONYMOUS">
                    order_container.animate({
                        marginTop:"-400"
                    }, 1500);
                </sec:authorize>
                } else {
                    alert(json.errorMessage);
                }

            },error:function() {
                alert("Ошибка отправки данных. Попробуйте еще раз!");
            }

        })
    }
}

function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
}
function isValidPhone(phoneNumber) {
    var intRegex = /[0-9 -()+]?$/;
    return intRegex.test(phoneNumber);
}

Order.cancel = function() {
    container.animate({
        marginTop:"-400"
    }, 1500);
    order_container.animate({
        marginTop:0
    }, 1000);
}


</script>

</head>

<body>
<div class="container_16">
    <jsp:include page="static/header.jsp"/>
    <jsp:include page="static/menu.jsp"/>
    <div class="grid_16 content">
        <div class="grid_10">
            <c:forEach var="lantern" items="${lanterns}">
                <dl>
                    <dt>
                        <a href="#" class="dev_img"><img
                                src="${lantern.imgUrl}"
                                alt="/img/source/air.jpg"
                                width="170px;"/></a>
                    <div class="price">
                        <p>${lantern.price}</p>
                    </div>
                    </dt>
                    <dd>
                        <p>${lantern.description}</p>
                    </dd>
                    <div class="order_container">
                        <form method="POST" action="#">
                            <table>
                                <tr>
                                    <td>
                                        <button type="button" onclick="minus('#amount_field_${lantern.idLantern}');"
                                                class="button green" id="minus_btn">-
                                        </button>
                                    </td>
                                    <td>
                                        <input type="text" value="0" class="digits"
                                               id="amount_field_${lantern.idLantern}"/>
                                    </td>
                                    <td>
                                        <button type="button" onclick="plus('#amount_field_${lantern.idLantern}');"
                                                class="button green" id="plus_btn">+
                                        </button>
                                    </td>
                                    <td>
                                        <button type="button" class="button red"
                                                onclick="Order.updateOrder(${lantern.idLantern}, '#amount_field_${lantern.idLantern}', ${lantern.price})">
                                            В корзину
                                        </button>
                                    </td>
                                </tr>
                            </table>
                        </form>
                    </div>
                </dl>
            </c:forEach>

        </div>
        <div class="grid_6" style="float:right">
            <c:if test="${not empty last_action.description}">
                <div class="title">
                    <h1>Акции</h1>

                    <div class="content">
                        <c:if test="${ not empty last_action.actionImage}">
                            <img src="${last_action.actionImage}" width="200px"/>
                        </c:if>
                            ${last_action.description}
                    </div>
                </div>
            </c:if>
        </div>
        <div class="grid_6" style="float:right;">
            <c:forEach var="small" items="${small_lanterns}">
                <dl class="small">
                    <dt>
                        <a href="#" class="dev_img"><img
                                src="${small.imgUrl}"
                                alt="/img/source/air.jpg"
                                width="170px;"/></a>
                    <div class="price">
                        <p>${small.price}</p>
                    </div>
                    </dt>
                    <dd>
                        <p>${small.description}</p>
                    </dd>
                    <div class="order_container">
                        <form method="POST" action="#">
                            <table>
                                <tr>
                                    <td>
                                        <button type="button" onclick="minus('#small_amount_field_${small.idLantern}');"
                                                class="button green" id="small_minus_btn">-
                                        </button>
                                    </td>
                                    <td>
                                        <input type="text" value="0" class="digits"
                                               id="small_amount_field_${small.idLantern}"/>
                                    </td>
                                    <td>
                                        <button type="button" onclick="plus('#small_amount_field_${small.idLantern}');"
                                                class="button green" id="small_plus_btn">+
                                        </button>
                                    </td>
                                    <td>
                                        <button type="button" class="button red"
                                                onclick="Order.updateOrder(${small.idLantern}, '#small_amount_field_${small.idLantern}', ${small.price})">
                                            В корзину
                                        </button>
                                    </td>
                                </tr>
                            </table>
                        </form>
                    </div>
                </dl>
            </c:forEach>
        </div>
    </div>
    <div class="clear"></div>
    <jsp:include page="static/footer.jsp"/>
</div>
<div class="absolute_container" id="absolute_container">
    <div class="result_order_container">
        <div class="title">
            <h1>Ваш заказ</h1>
            <a href="javascript:void(0)" id="close"><img src="/img/icons/close.png"></a>
        </div>
        <div class="result_order">
            <ul id="list">
            </ul>
            <div class="total_sum">
            </div>
            <div class="send_container">
                <sec:authorize ifAnyGranted="ROLE_ANONYMOUS">
                    <button type="button" class="button red" id="send_btn" onclick="Order.showCred()">Оформить
                        заказ
                    </button>
                </sec:authorize>

                <sec:authorize ifNotGranted="ROLE_ANONYMOUS">
                    <button type="button" class="button red" id="send_btn" onclick="Order.sendOrder(myOrders)">Оформить
                        заказ
                    </button>
                </sec:authorize>
            </div>
        </div>
    </div>
    <div class="open">

    </div>

    <div class="credential_container">
        <div class="title">
            <h1>Ваши данные</h1>
        </div>
        <div class="credentials">
            <div class="item">
                <label for="cred_email">Email</label>

                <div class="field">
                    <input type="text" value="" id="cred_email"/>
                </div>
            </div>
            <div class="item">
                <label for="cred_phone">Телефон</label>

                <div class="field">
                    <input type="text" value="" id="cred_phone"/>
                </div>
            </div>
            <div class='send_container'>
                <button class="button red" type="button" onclick="Order.sendOrder(myOrders)">Отправить</button>
                <button class="button red" type="button" onclick="Order.cancel()">Отменить</button>
            </div>
        </div>
    </div>

</div>
</body>
</html>